//
//  HMMainViewController.swift
//  SinaWeiBo
//
//  Created by immncjykeny on 2017/4/21.
//  Copyright © 2017年 immncjykeny. All rights reserved.
//

import UIKit
import SVProgressHUD

class HMMainViewController: UITabBarController {
    
    //定时器 定是检测新微博数据
     fileprivate var timer:Timer?
    
    //设置撰写按钮
     lazy var composeButton:UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
    
    //在swift 中 没有.h和.m文件 所以要写上private 保护函数 当然需要调用的时候 再去掉 用来保护函数的作用
   func composeStatus(){
        print("点击撰写按钮")
       //测试横屏方向 使用modal
      let vc = UIViewController()
    
     vc.view.backgroundColor = UIColor.cz_random()
    
    let nav = UINavigationController(rootViewController: vc)
    
       
    present(nav, animated: true, completion: nil)
    
    }
    
    //用代码设置设备方向支持 一旦设置 当前控制器以及子控制器都遵守这个方向
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        
        return .portrait
    }
    

    override func viewDidLoad() {
        
        super.viewDidLoad()
      
        
        setupChildControllers()
        
        setupComposeButton()
        
         setupTimer()
        
        setupNewFeatureViews()
        
        //这一步设置UITabbarcontrollerdelegate 代理不要用问号 要不然代理方法没有用
        delegate = self
        //注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name: NSNotification.Name(rawValue: HMUserShouldLoginNotification), object: nil)
       
        
    }
    //销毁通知 定时器 KVO必须销毁 否则直接崩溃
    deinit {
        timer?.invalidate()
       
        //注销通知
        NotificationCenter.default.removeObserver(self)
    }
    @objc private func userLogin(n:Notification){
        //判断n.object是否有值 如果有值 需要重新登录
        
        var when = DispatchTime.now()
        if n.object != nil {
            SVProgressHUD.setDefaultMaskType(.gradient)
            SVProgressHUD.showInfo(withStatus: "用户登录超时,需要重新登录")
            when = DispatchTime.now() + 2
        }
            print("用户登录通知\(n)")
        
            DispatchQueue.main.asyncAfter(deadline: when, execute: {
                
                SVProgressHUD.setDefaultMaskType(.clear)
                
                let nav = UINavigationController(rootViewController: HMOAuthViewController())
                
                self.present(nav, animated: true, completion: nil)
            })
        
        
    }
   
}
extension HMMainViewController{
    //检测新特性方法
    fileprivate func setupNewFeatureViews(){
        //1.检测是否有新特性
        
        //2.如果版本不一致 就展示新特性 否则 就是欢迎界面
        let v = isNewVersion ? HMNewFeatureView.newFeatureView() : HMWelcomeView.welcomeView()
        
        
        //3.添加视图
        
        view.addSubview(v)
        
    }
    //extension 可以有计算型属性 类似于一个函数 不占有内存空间
    private var isNewVersion:Bool{
        
        //1.取当前版本号
        
        print(Bundle.main.infoDictionary ?? "")
        
        let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
        print("当前版本" + "\(currentVersion)")
        
        //2.取保存在目录(Document iTunes自动备份 最好是偏好设置)之前的版本号
        
        let path:String = ("version" as NSString).cz_appendDocumentDir()
        
        print(path)
        
        let sandBoxVersion = (try? String(contentsOfFile: path)) ?? ""
        
        print("沙盒版本" + "\(sandBoxVersion)")
        //3.在保存当前版本号
        
       _ = try? currentVersion.write(toFile: path, atomically: true, encoding: .utf8)
        
        //4.返回版本号是否一致
        //return currentVersion != sandBoxVersion
        return currentVersion != sandBoxVersion
       
    }
}
extension HMMainViewController:UITabBarControllerDelegate{
    
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        
       
        //解决目标控制器中间按钮容错问题
        //1.获取控制器在数组中的索引
        let idx = (childViewControllers as NSArray).index(of: viewController)
        //拿到当前home的首页 并且索引也是当前的页面
        if selectedIndex == 0 && idx == selectedIndex {
            print("点击首页")
            //让表格滚动到底顶层
            let nav = childViewControllers[0] as! UINavigationController
            let vc = nav.childViewControllers[0] as! HMHomeViewController
            vc.tableView?.setContentOffset(CGPoint(x: 0,y: -64), animated: true)
            //刷新数据
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: { 
                vc.loadData()
            })
            
        }
        
        return !viewController.isMember(of: UIViewController.self)
    }
}
extension HMMainViewController{
    //创建一个定时器
    fileprivate func setupTimer(){
        timer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    }
    //定时器触发方法
    @objc private func updateTimer(){
        
        if !HMShareManager.shared.userlogon {
            return
        }
        HMShareManager.shared.unreadCount { (count) in
            print("检测到\(count)条新微博")
            //设置首页tabbar的badgevalue
            self.tabBar.items?[0].badgeValue = count > 0 ? "\(count)" :nil
            //设置APP的badgenumber 在iOS8.0之后需要授权
            UIApplication.shared.applicationIconBadgeNumber = count
        }
    }
    
    
    
}

extension HMMainViewController{
    //创建中间按钮
     func setupComposeButton(){
        
        tabBar.addSubview(composeButton)
        let count = CGFloat(childViewControllers.count)
        //这一行代码就是为了解决容错问题
        let w = tabBar.bounds.width / count
        
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        
        composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
        
    }
    ///设置所有子控制器
     fileprivate func setupChildControllers(){
        //第二次加载沙盒已经有这个json文件了 直接动态修改 数据参数
        let  docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
        
        var data = NSData(contentsOfFile: jsonPath)
        //如果沙盒没有json 直接从bundle拿去 也就是默认的
        if  data == nil {
            let path = Bundle.main.path(forResource: "main.json", ofType: nil)
            
             data = NSData(contentsOfFile: path!)
            
        }
        
        //反序列化
        guard let array = try? JSONSerialization.jsonObject(with:data! as Data, options: []) as? [[String:Any]]
            else{
            return
        }
//        let array:[[String:Any]] = [["clsName":"HMHomeViewController","title":"首页","imageName":"tabbar_home","visitorInfo":["imageName":"","message":"关注一些人,看看这里有什么惊喜"]],
//            ["clsName":"HMMessageViewController","title":"消息","imageName":"tabbar_message_center","visitorInfo":["imageName":"visitordiscover_image_message","message":"登陆后,别人发给你的消息,别人评论你的微薄,都会在这里收到通知"]],
//            ["clsName":"UIViewController"],
//            ["clsName":"HMDiscoverViewController","title":"发现","imageName":"tabbar_discover",
//             "visitorInfo":["imageName":"visitordiscover_image_message","message":"登陆后,最新,最热的微博尽在掌握,不会再与时事潮流擦肩而过"]],["clsName":"HMProfileViewController","title":"我","imageName":"tabbar_profile","visitorInfo":["imageName":"visitordiscover_image_profile","message":"登陆后,你的微薄,相册,个人资料会显示在这里,展示给别人"]]
//        ]
//        //验证测试是否是json格式数据
//        (array as NSArray) .write(toFile: "/Users/immncjykeny/Desktop/demo.plist", atomically: true)
//        //将数组或者字典转化成二进制是序列化 反之 就是反序列化
//        let data = try! JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
//        let fileUrl = NSURL.fileURL(withPath: "/Users/immncjykeny/Desktop/main.json")
//        (data as NSData) .write(to: fileUrl, atomically: true)
        
        var arrayM = [UIViewController]()
        
        for dict in array! {
            arrayM.append(controller(dict: dict))
            
        }
        viewControllers = arrayM
        
        
    }
    //使用字典创建一个子控制器
    private func controller(dict:[String:Any]) -> UIViewController {
        //获取字典内容
        guard let clsName = dict["clsName"] as? String ,
              let title = dict["title"] as? String,
              let imageName = dict["imageName"] as? String,
              let visitorDict = dict["visitorInfo"] as? [String:String],
              let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? HMBaseViewController.Type
             else {
            return UIViewController()
        }
        //使用反射机制
        let vc = cls.init()
        
        vc.title = title
        //设置访客字典信息
        vc.visitorInfoDictionary = visitorDict
        
        vc.tabBarItem.image = UIImage(named: imageName)
        
        vc.tabBarItem.selectedImage = UIImage(named: imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        //实体化navigationController
        let nav = HMNavigaViewController(rootViewController: vc)
        
        vc.tabBarItem.setTitleTextAttributes(
        [NSForegroundColorAttributeName:UIColor.orange], for: .highlighted)
        
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 12)], for: .normal)
        //这是多态
        return nav
        
    }
}
